<?php

class OrdersController extends AppController {

    var $name = 'Orders';
    var $uses = array('Order', 'Article', 'Supplier', 'Purchase'); //aca le decis cuales modelos vas a usar

    function beforeFilter() {
        parent::beforeFilter();

        //si no es un usuario con nivel = 2 o 1 no lo dejo acceder a las siguientes funciones de este controlador
        if (in_array($this->action, array('index', 'add', 'delete', 'view', 'confirm', 'listapdf')) and $this->Auth->user('id') and !(in_array($this->Auth->user('level'), array(1,2)))) {
            $this->redirect(array('user' => false, 'controller' => 'articles', 'action' => 'inicio'));
        }
    }
    
    function index() {
        $this->Order->recursive = 0;
        $this->paginate['order'] = array('Order.date' => 'DESC');
        $this->set('orders', $this->paginate());
    }
    
    function listapdf(){
        //C:\xampp\htdocs\cerrajeria\app\vendors
        require('/app/vendors/fpdf/fpdf.php');

        $pdf = new FPDF();
        $pdf->AddPage();
        $pdf->SetFont('Arial','B',16);
        $pdf->SetMargins(1,1.5,1.5);
        
        $articles = $this->Order->find('all', array('conditions' => array('Order.date_recibed' => NULL, 'Order.amount_recibed' => NULL)));
        $pdf->Image(SITE_URL . '/img/pdf_logo.JPG', 170, 5, 30);
        $pdf->Text(10,15,'Pedidos Sin Confirmar');
        // Salto de línea
        $pdf->Ln(10);
        $pdf->Line(10, 20, 200, 20);
        
        $pdf->SetFont('Arial','B',12);
        $pdf->SetXY(10, 40);
        $pdf->Cell(40, 5, 'Marca', 1, 'C', 1);
        $pdf->SetXY(50, 40);
        $pdf->Cell(40, 5, 'Modelo', 1, 'C', 1);
        $pdf->SetXY(90, 40);
        $pdf->Cell(25, 5, 'Fecha', 1, 'C', 1);    
        $pdf->SetXY(115, 40);
        $pdf->Cell(25, 5, 'Cantidad', 1, 'C', 1);
        $pdf->SetXY(140, 40);
        $pdf->Cell(30, 5, 'Fecha Rec.', 1, 'C', 1);    
        $pdf->SetXY(170, 40);
        $pdf->Cell(30, 5, 'Cantidad Rec.', 1, 'C', 1);
        $y = 50;
        $pdf->SetFillColor(255, 255, 255);
        $pdf->SetFont('Arial','',11);
        
        foreach($articles as $art){
            $pdf->SetXY(10, $y);
            $pdf->Cell(40, 5, $art['Article']['mark'], 1, 'C', 1);
            $pdf->SetXY(50, $y);
            $pdf->Cell(40, 5, $art['Article']['model'], 1, 'C', 1);
            $pdf->SetXY(90, $y);
            $pdf->Cell(25, 5, date('d/m/Y', strtotime($art['Order']['date'])), 1, 'C', 1);    
            $pdf->SetXY(115, $y);
            $pdf->Cell(25, 5, $art['Order']['amount'], 1, 'C', 1);
            $pdf->SetXY(140, $y);
            $pdf->Cell(30, 5, '', 1, 'C', 1);    
            $pdf->SetXY(170, $y);
            $pdf->Cell(30, 5, '', 1, 'C', 1);
            $y +=+5;

            if ($y > 280){
                $pdf->AddPage();
                $pdf->SetFont('Arial','B',12);
                $pdf->SetXY(10, 40);
                $pdf->Cell(40, 5, 'Marca', 1, 'C', 1);
                $pdf->SetXY(50, 40);
                $pdf->Cell(40, 5, 'Modelo', 1, 'C', 1);
                $pdf->SetXY(90, 40);
                $pdf->Cell(20, 5, 'Fecha', 1, 'C', 1);    
                $pdf->SetXY(110, 40);
                $pdf->Cell(30, 5, 'Cantidad', 1, 'C', 1);
                $pdf->SetXY(140, 40);
                $pdf->Cell(30, 5, 'Fecha Rec.', 1, 'C', 1);    
                $pdf->SetXY(170, 40);
                $pdf->Cell(30, 5, 'Cantidad Rec.', 1, 'C', 1);
                $y = 50;
                $pdf->SetFillColor(255, 255, 255);
                $pdf->SetFont('Arial','',11);    
                $y = 50;
                $pdf->SetFillColor(255, 255, 255);
                $pdf->SetFont('Arial','',11);
            }
        }

        $pdf->Text(10,275,"Fecha: ".date("d/m/Y")."\n\n");
        $pdf->Text(10,280,"Hora: ".date("H:i:s")."\n\n");
        $pdf->Output();

    }

    function view($id = null) {
        if (!$id) {
            $this->Session->setFlash(__('Invalid order', true));
            $this->redirect(array('action' => 'index'));
        }
        $this->set('order', $this->Order->read(null, $id));
    }

    function add($id = null) {
        if (!empty($this->data)) {
            $array_datos = $this->data;
            if($array_datos['Order']['date'] != NULL){
                list($d, $m, $a) = explode("/", $array_datos['Order']['date']);
                $fecha_aux = $a . "-" . $m . "-" . $d;
                $array_datos['Order']['date'] = $fecha_aux;
                $fecha_actual = date('Y-m-d');
                if($fecha_aux <= $fecha_actual){
                    $this->Order->create();
                    if ($this->Order->save($array_datos)) {
        //                $this->Session->setFlash(__('The order has been saved', true));
                        $this->redirect(array('controller' => 'articles','action' => 'index'));
                    }
                }else {
                    $this->Session->setFlash(__('El pedido no pudo ser guardado. Verifique que la fecha de emision no sea mayor que la actual.', true));
                }
            }else{
                $this->Session->setFlash(__('Debe Completar los datos.', true));
            }
        }
        $articulos = $this->Article->find('all', array('fields' => array('Article.mark', 'Article.model', 'Article.id'), 'conditions' => array('Article.termination_date' => NULL)));
        $articles = array();
        foreach ($articulos as $art) {
            $articles[$art['Article']['id']] = $art['Article']['mark'] . ' - ' . $art['Article']['model'];
        }
        $ultimo_proveedor = $this->Order->query("SELECT suppliers.id as id FROM suppliers, purchases, articles WHERE suppliers.id = purchases.supplier_id AND purchases.article_id = " . $id . " order by purchases.purchase_date desc LIMIT 1");
        $this->set('ultimo_proveedor', $ultimo_proveedor);
        $suppliers = $this->Order->Supplier->find('list');
        $this->set(compact('articles', 'suppliers'));
        $this->set('art_id', $id);
    }

    function confirm($id = null) {
        //empiezo una transaccion
        $this->Article->query('SET AUTOCOMMIT = 0;');
        $this->Article->query('START TRANSACTION;');
        $bandera = true; //la uso para ver si algo salio mal
        
        if (!$id && empty($this->data)) {
            $this->Session->setFlash(__('Invalid order', true));
            $this->redirect(array('action' => 'index'));
        }
        if (!empty($this->data)) {
            $array_datos = $this->data;
            if($array_datos['Order']['date_recibed'] != NULL and $array_datos['Order']['amount_recibed'] != NULL){
                list($d, $m, $a) = explode("/", $array_datos['Order']['date']);
                $fecha_aux = $a . "-" . $m . "-" . $d;
                $array_datos['Order']['date'] = $fecha_aux;

                if ($array_datos['Order']['date_recibed'] != NULL) {
                    list($d, $m, $a) = explode("/", $array_datos['Order']['date_recibed']);
                    $fecha_aux = $a . "-" . $m . "-" . $d;
                    $array_datos['Order']['date_recibed'] = $fecha_aux;
                }
                $fecha_actual = date('Y-m-d');
                if($array_datos['Order']['date_recibed'] <= $fecha_actual){
                    if ($this->Order->save($array_datos)) {
        //                $this->Session->setFlash(__('The order has been saved', true));
        //                $this->redirect(array('action' => 'index'));
                        $order_id = $this->Order->id;

                        $compra = array();
                        $compra['article_id'] = $this->data['Order']['article_id'];
                        $compra['purchase_date'] = $this->data['Order']['date_recibed'];
                        $compra['purchase_amount'] = $this->data['Order']['amount_recibed'];
                        $compra['supplier_id'] = $this->data['Order']['supplier_id'];
                        $compra['order_id'] = $order_id;

                        list($d, $m, $a) = explode("/", $compra['purchase_date']);
                        $fecha_aux = $a . "-" . $m . "-" . $d;
                        $compra['purchase_date'] = $fecha_aux;

                        $this->Purchase->create();
                        if ($this->Purchase->save($compra)) {
                            //Ahora actualizo el stock del articulo
                            $aux = $this->Article->find('first', array('conditions' => array('Article.id' => $this->data['Order']['article_id'])));
                            $aux['Article']['amount_available'] = $aux['Article']['amount_available'] + $this->data['Order']['amount_recibed'];
                            if ($this->Article->save($aux)) {
                                $bandera = true;
                            } else{
                                $bandera = false;
                            }
                        } else {
                            $bandera = false;
                        }
                    } else {
                        $bandera = false;
                    }
                }else{
                    $bandera = false;
                }
            }else{
                $bandera = false;
//                $this->Session->setFlash(__('Debe completar los datos.', true));
            }
            //Transcations
            if ($bandera) {
                $this->Order->query('COMMIT;');
                $this->Order->query('SET AUTOCOMMIT = 1;');
                $this->redirect(array('action' => 'index'));
            } else {//si hubo algun error hago un ROLLBACK deshaciendo todas estas consultas
                $this->Order->query('ROLLBACK;');
                $this->Order->query('SET AUTOCOMMIT = 1;');
                $this->Session->setFlash(__('El pedido no se pudo guardar. Por favor, inténtelo de nuevo.', true));
            }
        }
        if (empty($this->data)) {
            $this->data = $this->Order->read(null, $id);
            $this->data['Order']['date'] = date('d/m/Y', strtotime($this->data['Order']['date']));
            if ($this->data['Order']['date_recibed'] != NULL) {
                $this->data['Order']['date_recibed'] = date('d/m/Y', strtotime($this->data['Order']['date_recibed']));
            }
        }
        $articulos = $this->Article->find('all', array('fields' => array('Article.mark', 'Article.model', 'Article.id'), 'conditions' => array('Article.termination_date' => NULL)));
        $articles = array();
        foreach ($articulos as $art) {
            $articles[$art['Article']['id']] = $art['Article']['mark'] . ' - ' . $art['Article']['model'];
        }
        $suppliers = $this->Order->Supplier->find('list');
        $this->set(compact('articles', 'suppliers'));
    }

    function edit($id = null) {
        if (!$id && empty($this->data)) {
            $this->Session->setFlash(__('Invalid order', true));
            $this->redirect(array('action' => 'index'));
        }
        if (!empty($this->data)) {
            $array_datos = $this->data;
            if(!empty($array_datos['Order']['date'])){
                list($d, $m, $a) = explode("/", $array_datos['Order']['date']);
                $fecha_aux = $a . "-" . $m . "-" . $d;
                $array_datos['Order']['date'] = $fecha_aux;
                $fecha_actual = date('Y-m-d');

                if($array_datos['Order']['date'] <= $fecha_actual){

                    if ($this->Order->save($array_datos)) {
    //                    $this->Session->setFlash(__('The order has been saved', true));
                        $this->redirect(array('action' => 'index'));
                    } else {
                        $this->Session->setFlash(__('El pedido no pudo guardarse. Por favor, intente de nuevo.', true));
                    }
                }else {
                    $this->Session->setFlash(__('El pedido no pudo guardarse. Verifique que las fechas no sean mayores que la actual.', true));
                }
            }else{
                $bandera=false;
                $this->Session->setFlash(__('El pedido no pudo guardarse. Verifique que las fechas no sean mayores que la actual.', true));
            }

        }
        if (empty($this->data)) {
            $this->data = $this->Order->read(null, $id);
            $this->data['Order']['date'] = date('d/m/Y', strtotime($this->data['Order']['date']));
            if ($this->data['Order']['date_recibed'] != NULL) {
                $this->data['Order']['date_recibed'] = date('d/m/Y', strtotime($this->data['Order']['date_recibed']));
            }
        }
        $articulos = $this->Article->find('all', array('fields' => array('Article.mark', 'Article.model', 'Article.id'), 'conditions' => array('Article.termination_date' => NULL)));
        $articles = array();
        foreach ($articulos as $art) {
            $articles[$art['Article']['id']] = $art['Article']['mark'] . ' - ' . $art['Article']['model'];
        }
        $suppliers = $this->Order->Supplier->find('list');
        $this->set(compact('articles', 'suppliers'));
    }

    function delete($id = null) {
        if (!$id) {
            $this->Session->setFlash(__('Invalid id for order', true));
            $this->redirect(array('action' => 'index'));
        }
        $purchases = $this->Purchase->find('list', array('conditions' => array('Purchase.order_id' => $id)));
        if(sizeof($purchases) == 0){
            if ($this->Order->delete($id)) {
//                $this->Session->setFlash(__('Order deleted', true));
                $this->redirect(array('action' => 'index'));
            }
        }else{
            $this->Session->setFlash(__('No es posible eliminar el pedido porque tiene compras asociadas.', true));
            $this->redirect(array('action' => 'index'));
        }
        $this->Session->setFlash(__('Pedido no eliminado', true));
        $this->redirect(array('action' => 'index'));
    }

}
